package io.gitee.twoke.generator.engine.impl.cmd;

import io.gitee.twoke.generator.engine.impl.generate.DataTable;
import io.gitee.twoke.generator.engine.impl.generate.DataTableColumn;
import io.gitee.twoke.generator.engine.impl.interceptor.Command;
import io.gitee.twoke.generator.engine.impl.interceptor.CommandContext;
import io.gitee.twoke.generator.engine.impl.persistence.entity.DataTableColumnEntity;
import io.gitee.twoke.generator.engine.impl.persistence.entity.DataTableEntity;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;

import java.util.List;
import java.util.Objects;

public class UpdateTableCmd implements Command<Void> {

    private DataTableEntity table;

    public UpdateTableCmd(DataTable table) {
        if (Objects.isNull(table) || Objects.isNull(table.getId())) {
            throw new IllegalArgumentException("table  is null");
        }
        if (!DataTableEntity.class.isAssignableFrom(table.getClass())) {
            throw new IllegalArgumentException("table  is not instance of " + DataTableEntity.class.getName());
        }
        this.table = (DataTableEntity) table;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        commandContext.getDataTableEntityManager().update(this.table);
        List<DataTableColumn> columns = this.table.getColumns();
        if (CollectionUtil.isNotEmpty(columns)) {
            for (DataTableColumn column : columns) {
                column.setTableId(this.table.getId());
                if (StrUtil.isBlank(column.getId())) {
                    throw new IllegalArgumentException("table column id is null");
                }
                commandContext.getDataTableColumnEntityManager().update((DataTableColumnEntity) column);
            }
        }
        return null;
    }
}
